package com.example.demo.test.lecture.httpstest;

import com.alibaba.csb.sdk.HttpCallerException;
import com.alibaba.csb.sdk.HttpReturn;
import com.alibaba.csb.sdk.SdkLogger;
import com.alibaba.csb.sdk.internel.HttpClientConnManager;
import com.alibaba.csb.sdk.security.SignUtil;
import com.example.demo.test.lecture.httpstest.ContentBody.Type;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.config.RequestConfig.Builder;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.concurrent.FutureCallback;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
import org.apache.http.impl.nio.client.HttpAsyncClients;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;

import java.io.*;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.*;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

public class HttpCaller {
    private static boolean warmupFlag = false;
    private static final String RESTFUL_PATH_SIGNATURE_KEY = "csb_restful_path_signature_key";
    private static final String DEFAULT_RESTFUL_PROTOCOL_VERSION = "1.0";
    private static final String RESTFUL_PROTOCOL_VERION_KEY = "restful_protocol_version";
    public static final String trustCA = System.getProperty("http.caller.ssl.trustca");
    private static final String DEFAULT_CHARSET = "UTF-8";
    private static String defaultAK = null;
    private static String defaultSK = null;
    private static ThreadLocal<Boolean> toCurlCmd = new ThreadLocal();
    private static ThreadLocal<HttpHost> proxyConfigThreadLocal = new ThreadLocal();
    private static final Builder requestConfigBuilder = HttpClientConnManager.createConnBuilder();
    private static final ThreadLocal<Builder> requestConfigBuilderLocal = new ThreadLocal();
    private static final long MAX_FILE_SIZE = 10485760L;

    private HttpCaller() {
    }

    public static synchronized void warmup() {
        if (!warmupFlag) {
            SignUtil.warmup();
            warmupFlag = true;
        }
    }

    public static void setProxyHost(String hostname, int port, String scheme) {
        proxyConfigThreadLocal.set(new HttpHost(hostname, port, scheme));
    }

    public static void setConnectionParams(Map<String, String> params) {
        if (params != null && params.size() != 0) {
            requestConfigBuilderLocal.set(HttpClientConnManager.createConnBuilder(params));
        } else {
            requestConfigBuilderLocal.set(requestConfigBuilder);
        }

    }

    private static RequestConfig getRequestConfig() {
        Builder rcBuilder = null;
        if (requestConfigBuilderLocal.get() == null) {
            rcBuilder = requestConfigBuilder;
        } else {
            rcBuilder = (Builder)requestConfigBuilderLocal.get();
        }

        rcBuilder.setProxy((HttpHost)proxyConfigThreadLocal.get());
        return rcBuilder.build();
    }

    public static void setCurlResponse(boolean flag) {
        toCurlCmd.set(true);
    }

    private static boolean isCurlResponse() {
        return toCurlCmd.get() != null && (Boolean)toCurlCmd.get();
    }

    public static void setCredential(String accessKey, String secretKey) {
        defaultAK = accessKey;
        defaultSK = secretKey;
    }

    public static String changeCharset(String result, String OldcharsetName, String charsetName) throws HttpCallerException {
        if (result == null) {
            return result;
        } else {
            try {
                return new String(result.getBytes(OldcharsetName), charsetName);
            } catch (UnsupportedEncodingException var4) {
                throw new HttpCallerException(var4);
            }
        }
    }

    public static String changeCharset(String result) throws HttpCallerException {
        return changeCharset(result, "ISO-8859-1", "UTF-8");
    }

    /** @deprecated */
    public static String doGet(String requestURL, String apiName, Map<String, String> paramsMap) throws HttpCallerException {
        return doGet(requestURL, apiName, paramsMap, defaultAK, defaultSK);
    }

    /** @deprecated */
    public static String doGet(String requestURL, String apiName, Map<String, String> paramsMap, String accessKey, String secretKey) throws HttpCallerException {
        return doGet(requestURL, apiName, (String)null, paramsMap, accessKey, secretKey);
    }

    /** @deprecated */
    public static String doGet(String requestURL, String apiName, String version, Map<String, String> paramsMap, String accessKey, String secretKey) throws HttpCallerException {
        return doGet(requestURL, apiName, version, paramsMap, accessKey, secretKey, (String)null, (String)null);
    }

    /** @deprecated */
    public static String doGet(String requestURL, String apiName, String version, Map<String, String> paramsMap, String accessKey, String secretKey, String signImpl, String verifySignImpl) throws HttpCallerException {
        HttpParameters hp = HttpParameters.newBuilder().requestURL(requestURL).api(apiName).version(version).putParamsMapAll(paramsMap).accessKey(accessKey).secretKey(secretKey).signImpl(signImpl).verifySignImpl(verifySignImpl).build();
        return doGet(hp, (Map)null).response;
    }

    public static Map<String, String> getCsbHeaders(String requestURL, String apiName, String version, Map<String, String> paramsMap, String accessKey, String secretKey) throws HttpCallerException {
        return getCsbHeaders(requestURL, apiName, version, paramsMap, accessKey, secretKey, (String)null, (String)null);
    }

    public static Map<String, String> getCsbHeaders(String requestURL, String apiName, String version, Map<String, String> paramsMap, String accessKey, String secretKey, String signImpl, String verifySignImpl) throws HttpCallerException {
        Map<String, List<String>> urlParamsMap = HttpClientHelper.parseUrlParamsMap(requestURL, true);
        HttpClientHelper.mergeParams(urlParamsMap, paramsMap, true);
        return HttpClientHelper.newParamsMap(urlParamsMap, apiName, version, accessKey, secretKey, true, false, (Map)null, (StringBuffer)null, signImpl, verifySignImpl);
    }

    private static HttpReturn doGet(HttpParameters hp, Map<String, String> extSignHeadersMap) throws HttpCallerException {
        String requestURL = hp.getRequestUrl();
        String apiName = hp.getApi();
        String version = hp.getVersion();
        Map<String, String> paramsMap = hp.getParamsMap();
        ContentBody cb = hp.getContentBody();
        String accessKey = hp.getAccessKey();
        String secretKey = hp.getSecretkey();
        Map<String, String> directParamsMap = hp.getHeaderParamsMap();
        String restfulProtocolVersion = hp.getRestfulProtocolVersion();
        HttpReturn ret = new HttpReturn();
        ret.diagnosticFlag = hp.isDiagnostic();
        long startT = System.currentTimeMillis();
        long initT = startT;
        DiagnosticHelper.setStartTime(ret, startT);
        HttpClientHelper.validateParams(apiName, accessKey, secretKey, paramsMap);
        Map<String, List<String>> urlParamsMap = HttpClientHelper.parseUrlParamsMap(requestURL, true);
        HttpClientHelper.mergeParams(urlParamsMap, paramsMap, true);
        if (SdkLogger.isLoggable()) {
            SdkLogger.print("--+++ prepare params costs = " + (System.currentTimeMillis() - startT) + " ms ");
        }

        startProcessRestful(requestURL, restfulProtocolVersion, urlParamsMap);
        StringBuffer signDiagnosticInfo = DiagnosticHelper.getSignDiagnosticInfo(ret);
        Map<String, String> headerParamsMap = HttpClientHelper.newParamsMap(urlParamsMap, apiName, version, accessKey, secretKey, hp.isTimestamp(), hp.isNonce(), extSignHeadersMap, signDiagnosticInfo, hp.getSignImpl(), hp.getVerifySignImpl());
        DiagnosticHelper.setSignDiagnosticInfo(ret, signDiagnosticInfo);
        endProcessRestful(restfulProtocolVersion, urlParamsMap, headerParamsMap);
        String newRequestURL = HttpClientHelper.generateAsEncodeRequestUrl(requestURL, urlParamsMap);
        if (isCurlResponse()) {
            StringBuffer curl = new StringBuffer("curl ");
            curl.append(HttpClientHelper.genCurlHeaders(directParamsMap));
            curl.append(HttpClientHelper.genCurlHeaders(headerParamsMap));
            curl.append(" -k ");
            curl.append("\"").append(newRequestURL).append("\"");
            ret.response = curl.toString();
            return ret;
        } else {
            DiagnosticHelper.calcRequestSize(ret, newRequestURL, (Map)null, (ContentBody)null);
            HttpGet httpGet = new HttpGet(newRequestURL);
            httpGet.setConfig(getRequestConfig());
            if (directParamsMap != null) {
                HttpClientHelper.setHeaders(httpGet, directParamsMap);
            }

            HttpClientHelper.setHeaders(httpGet, headerParamsMap);
            DiagnosticHelper.setRequestHeaders(ret, httpGet.getAllHeaders());

            HttpReturn var21;
            try {
                ret = doHttpReq(requestURL, httpGet, ret);
                DiagnosticHelper.setEndTime(ret, System.currentTimeMillis());
                DiagnosticHelper.setInvokeTime(ret, System.currentTimeMillis() - initT);
                var21 = ret;
            } finally {
                if (SdkLogger.isLoggable()) {
                    SdkLogger.print("-- total = " + (System.currentTimeMillis() - startT) + " ms ");
                }

            }

            return var21;
        }
    }

    private static void endProcessRestful(String restfulProtocolVersion, Map<String, List<String>> urlParamsMap, Map<String, String> headerParamsMap) {
        if ("1.0".equals(restfulProtocolVersion)) {
            urlParamsMap.remove("csb_restful_path_signature_key");
            headerParamsMap.put("restful_protocol_version", "1.0");
        }

    }

    private static void startProcessRestful(String requestURL, String restfulProtocolVersion, Map<String, List<String>> urlParamsMap) throws HttpCallerException {
        if ("1.0".equals(restfulProtocolVersion)) {
            String path = HttpClientHelper.getUrlPathInfo(requestURL);
            if (path == null) {
                throw new HttpCallerException("this request is restful but the request path is　null !");
            }

            List<String> values = new ArrayList();
            values.add(path);
            urlParamsMap.put("csb_restful_path_signature_key", values);
        }

    }

    private static boolean isSSLProtocol(String requestUrl) {
        if (requestUrl == null) {
            return false;
        } else {
            return requestUrl.trim().toLowerCase().startsWith("https://");
        }
    }

    private static CloseableHttpClient createSyncHttpClient(String requestURL) throws HttpCallerException {
        CloseableHttpClient httpClient = null;
        if (isSSLProtocol(requestURL)) {
            try {
                httpClient = HttpClients.custom().setSslcontext((new SSLContextBuilder()).loadTrustMaterial((KeyStore)null, new TrustStrategy() {
                    public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                        return true;
                    }
                }).build()).setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
            } catch (KeyManagementException var3) {
                throw new HttpCallerException(var3);
            } catch (NoSuchAlgorithmException var4) {
                throw new HttpCallerException(var4);
            } catch (KeyStoreException var5) {
                throw new HttpCallerException(var5);
            }
        } else {
            httpClient = HttpClients.createDefault();
        }

        return httpClient;
    }

    private static CloseableHttpAsyncClient createAsyncHttpClient(String requestURL) throws HttpCallerException {
        CloseableHttpAsyncClient httpClient = null;
        if (isSSLProtocol(requestURL)) {
            try {
                httpClient = HttpAsyncClients.custom().setSSLHostnameVerifier(new NoopHostnameVerifier()).setSSLContext((new SSLContextBuilder()).loadTrustMaterial((KeyStore)null, new TrustStrategy() {
                    public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
                        return true;
                    }
                }).build()).build();
            } catch (KeyManagementException var3) {
                throw new HttpCallerException(var3);
            } catch (NoSuchAlgorithmException var4) {
                throw new HttpCallerException(var4);
            } catch (KeyStoreException var5) {
                throw new HttpCallerException(var5);
            }
        } else {
            httpClient = HttpAsyncClients.createDefault();
        }

        httpClient.start();
        return httpClient;
    }

    public static String doGet(String requestURL) throws HttpCallerException {
        HttpGet httpGet = new HttpGet(requestURL);
        httpGet.setConfig(getRequestConfig());
        HttpClientHelper.printDebugInfo("requestURL=" + requestURL);
        return doHttpReq(requestURL, httpGet, (HttpReturn)null).response;
    }

    /** @deprecated */
    public static String doPost(String requestURL, String apiName, Map<String, String> paramsMap) throws HttpCallerException {
        return doPost(requestURL, apiName, (String)null, paramsMap);
    }

    /** @deprecated */
    public static String doPost(String requestURL, String apiName, String version, Map<String, String> paramsMap) throws HttpCallerException {
        return doPost(requestURL, apiName, version, paramsMap, defaultAK, defaultSK);
    }

    /** @deprecated */
    public static String doPost(String requestURL, String apiName, Map<String, String> paramsMap, String accessKey, String secretKey) throws HttpCallerException {
        return doPost(requestURL, apiName, paramsMap, accessKey, secretKey, (String)null, (String)null);
    }

    /** @deprecated */
    public static String doPost(String requestURL, String apiName, Map<String, String> paramsMap, String accessKey, String secretKey, String signImpl, String verifySignImpl) throws HttpCallerException {
        return doPost(requestURL, apiName, (String)null, (Map)paramsMap, accessKey, secretKey, signImpl, verifySignImpl);
    }

    /** @deprecated */
    public static String doPost(String requestURL, String apiName, String version, ContentBody cb, String accessKey, String secretKey) throws HttpCallerException {
        return doPost(requestURL, apiName, version, (ContentBody)cb, accessKey, secretKey, (String)null, (String)null);
    }

    /** @deprecated */
    public static String doPost(String requestURL, String apiName, String version, ContentBody cb, String accessKey, String secretKey, String signImpl, String verifySignImpl) throws HttpCallerException {
        HttpParameters hp = HttpParameters.newBuilder().requestURL(requestURL).api(apiName).version(version).contentBody(cb).accessKey(accessKey).secretKey(secretKey).signImpl(signImpl).verifySignImpl(verifySignImpl).build();
        return doPost(hp, (Map)null).response;
    }

    private static HttpReturn doPost(HttpParameters hp, Map<String, String> extSignHeadersMap) throws HttpCallerException {
        String requestURL = hp.getRequestUrl();
        String apiName = hp.getApi();
        String version = hp.getVersion();
        Map<String, String> paramsMap = hp.getParamsMap();
        ContentBody cb = hp.getContentBody();
        String accessKey = hp.getAccessKey();
        String secretKey = hp.getSecretkey();
        Map<String, String> directHheaderParamsMap = hp.getHeaderParamsMap();
        String restfulProtocolVersion = hp.getRestfulProtocolVersion();
        boolean nonceFlag = hp.isNonce();
        HttpReturn ret = new HttpReturn();
        ret.diagnosticFlag = hp.isDiagnostic();
        long startT = System.currentTimeMillis();

        DiagnosticHelper.setStartTime(ret, startT);
        HttpClientHelper.validateParams(apiName, accessKey, secretKey, paramsMap);
        Map<String, List<String>> urlParamsMap = HttpClientHelper.parseUrlParamsMap(requestURL, true);
        String newRequestURL = HttpClientHelper.generateAsEncodeRequestUrl(requestURL, urlParamsMap);
        HttpClientHelper.mergeParams(urlParamsMap, paramsMap, false);
        startProcessRestful(newRequestURL, restfulProtocolVersion, urlParamsMap);
        if (cb != null && cb.getContentType() == Type.JSON && hp.isSignContentBody()) {
            urlParamsMap.put(ContentBody.CONTENT_BODY_SIGN_KEY, Arrays.asList((String)cb.getContentBody()));
        }

        StringBuffer signDiagnosticInfo = DiagnosticHelper.getSignDiagnosticInfo(ret);
        System.out.println("signInfo：" + signDiagnosticInfo);
        System.out.println("urlParamsMap: " + urlParamsMap.toString());
        System.out.println("extSignHeadersMap: " + extSignHeadersMap.toString());
        System.out.println("signDiagnosticInfo: " + signDiagnosticInfo);
        System.out.println("hp.getSignImpl(): " + hp.getSignImpl());
        System.out.println("hp.getVerifySignImpl(): " + hp.getVerifySignImpl());
        Map<String, String> headerParamsMap = HttpClientHelper.newParamsMap(urlParamsMap, apiName, version, accessKey, secretKey, true, nonceFlag, extSignHeadersMap, signDiagnosticInfo, hp.getSignImpl(), hp.getVerifySignImpl());
        DiagnosticHelper.setSignDiagnosticInfo(ret, signDiagnosticInfo);
        endProcessRestful(restfulProtocolVersion, urlParamsMap, headerParamsMap);
        if (isCurlResponse()) {
            return null;
//            return new HttpReturn(HttpClientHelper.createPostCurlString(newRequestURL, paramsMap, headerParamsMap, cb, directHheaderParamsMap));
        } else {
            DiagnosticHelper.calcRequestSize(ret, newRequestURL, paramsMap, cb);
            System.out.println("newRequestURL: " + newRequestURL +", paramsMap: " + paramsMap.toString()
                    + ", cb: " + cb.getContentBody() + ", headerParamsMap: " + headerParamsMap);
            HttpPost httpPost = HttpClientHelper.createPost(newRequestURL, paramsMap, headerParamsMap, cb);
            DiagnosticHelper.setRequestHeaders(ret, httpPost.getAllHeaders());
            HttpClientHelper.setDirectHeaders(httpPost, directHheaderParamsMap);
            httpPost.setConfig(getRequestConfig());
            if (SdkLogger.isLoggable()) {
                SdkLogger.print("-- prepare time = " + (System.currentTimeMillis() - startT) + " ms ");
            }

            HttpReturn var20;
            try {
                ret = doHttpReq(newRequestURL, httpPost, ret);
                DiagnosticHelper.setEndTime(ret, System.currentTimeMillis());
                DiagnosticHelper.setInvokeTime(ret, System.currentTimeMillis() - startT);
                var20 = ret;
            } finally {
                if (SdkLogger.isLoggable()) {
                    SdkLogger.print("-- total = " + (System.currentTimeMillis() - startT) + " ms ");
                }

            }

            return var20;
        }
    }

    private static HttpReturn doHttpReq(String requestURL, HttpRequestBase httpRequestBase, HttpReturn ret) throws HttpCallerException {
        boolean async = isAsync();
        return async ? doAsyncHttpReq(requestURL, httpRequestBase, ret) : doSyncHttpReq(requestURL, httpRequestBase, ret);
    }

    private static HttpReturn doSyncHttpReq(String requestURL, HttpRequestBase httpRequestBase, HttpReturn ret) throws HttpCallerException {
        if (SdkLogger.isLoggable()) {
            SdkLogger.print("doSyncHttpReq ");
        }

        HttpReturn rret = ret;
        if (ret == null) {
            rret = new HttpReturn();
        }

        long startT = System.currentTimeMillis();
        CloseableHttpResponse response = null;
        CloseableHttpClient httpClient = null;
        if (HttpClientConnManager.HTTP_CLIENT != null) {
            httpClient = HttpClientConnManager.HTTP_CLIENT;
        } else {
            httpClient = createSyncHttpClient(requestURL);
        }

        if (SdkLogger.isLoggable()) {
            SdkLogger.print("--+++ get httpclient costs = " + (System.currentTimeMillis() - startT) + " ms ");
            startT = System.currentTimeMillis();
        }

        try {
            HttpReturn var8;
            try {
                response = httpClient.execute(httpRequestBase);
                rret.responseHttpStatus = response.getStatusLine().toString();
                rret.responseHeaders = HttpClientHelper.fetchResHeaders(response);
                rret.response = EntityUtils.toString(response.getEntity());
                var8 = rret;
            } finally {
                if (response != null) {
                    response.close();
                }

                if (HttpClientConnManager.HTTP_CLIENT == null) {
                    httpClient.close();
                }

                if (SdkLogger.isLoggable()) {
                    SdkLogger.print("-- http req & resp time = " + (System.currentTimeMillis() - startT) + " ms ");
                }

            }

            return var8;
        } catch (Exception var13) {
            throw new HttpCallerException(var13);
        }
    }

    private static HttpReturn doAsyncHttpReq(String requestURL, HttpRequestBase httpRequestBase, HttpReturn ret) throws HttpCallerException {
        if (SdkLogger.isLoggable()) {
            SdkLogger.print("doAsyncHttpReq ");
        }

        HttpReturn rret = ret;
        if (ret == null) {
            rret = new HttpReturn();
        }

        long startT = System.currentTimeMillis();
        HttpResponse response = null;
        CloseableHttpAsyncClient httpClient = createAsyncHttpClient(requestURL);
        if (SdkLogger.isLoggable()) {
            SdkLogger.print("--+++ get httpclient costs = " + (System.currentTimeMillis() - startT) + " ms ");
            startT = System.currentTimeMillis();
        }

        try {
            HttpReturn var11;
            try {
                httpClient.start();
                Future<HttpResponse> asyncFuture = httpClient.execute(httpRequestBase, (FutureCallback)null);
                long waitTime = getFutureGetTimeOut();
                if (SdkLogger.isLoggable()) {
                    SdkLogger.print("future waitTime :" + waitTime);
                }

                if (waitTime > 0L) {
                    response = (HttpResponse)asyncFuture.get(waitTime, TimeUnit.MILLISECONDS);
                } else {
                    response = (HttpResponse)asyncFuture.get();
                }

                rret.response = EntityUtils.toString(response.getEntity());
                rret.responseHttpStatus = response.getStatusLine().toString();
                rret.responseHeaders = HttpClientHelper.fetchResHeaders(response);
                var11 = rret;
            } finally {
                httpClient.close();
                if (SdkLogger.isLoggable()) {
                    SdkLogger.print("-- http req & resp time = " + (System.currentTimeMillis() - startT) + " ms ");
                }

            }

            return var11;
        } catch (Exception var16) {
            throw new HttpCallerException(var16);
        }
    }

    /** @deprecated */
    public static String doPost(String requestURL, String apiName, String version, Map<String, String> paramsMap, String accessKey, String secretKey) throws HttpCallerException {
        return doPost(requestURL, apiName, version, (Map)paramsMap, accessKey, secretKey, (String)null, (String)null);
    }

    /** @deprecated */
    public static String doPost(String requestURL, String apiName, String version, Map<String, String> paramsMap, String accessKey, String secretKey, String signImpl, String verifySignImpl) throws HttpCallerException {
        HttpParameters hp = HttpParameters.newBuilder().requestURL(requestURL).api(apiName).version(version).putParamsMapAll(paramsMap).accessKey(accessKey).secretKey(secretKey).signImpl(signImpl).verifySignImpl(verifySignImpl).build();
        return doPost(hp, (Map)null).response;
    }

    public static String invoke(HttpParameters hp, StringBuffer resHttpHeaders) throws HttpCallerException {
        HttpReturn res = invokeReturn(hp);
        if (resHttpHeaders != null && res.responseHeaders != null) {
            resHttpHeaders.setLength(0);
            resHttpHeaders.append(res.responseHeaders);
        }

        return res.response;
    }

    public static HttpReturn invokeReturn(HttpParameters hp) throws HttpCallerException {
        if (hp == null) {
            throw new IllegalArgumentException("null parameter!");
        } else {
            HttpClientHelper.printDebugInfo("-- httpParameters=" + hp.toString());
            hp.validate();
            Map<String, String> extSignHeaders = new HashMap();
            return !"POST".equalsIgnoreCase(hp.getMethod()) && !"CPOST".equalsIgnoreCase(hp.getMethod()) ? doGet(hp, extSignHeaders) : doPost(hp, extSignHeaders);
        }
    }

    public static String invoke(HttpParameters hp) throws HttpCallerException {
        return invoke(hp, (StringBuffer)null);
    }

    public static byte[] readFileAsByteArray(String file) throws HttpCallerException {
        File f = new File(file);
        if (f.exists() && f.isFile() && f.canRead()) {
            if (f.length() > 10485760L) {
                throw new HttpCallerException("file is too large exceed the MAX-SIZE: 10M");
            } else {
                InputStream ios = null;
                ByteArrayOutputStream bos = null;
                Object var4 = null;

                try {
                    ios = new FileInputStream(file);
                    bos = new ByteArrayOutputStream();
                    byte[] b = new byte[1024];

                    int n;
                    while((n = ios.read(b)) != -1) {
                        bos.write(b, 0, n);
                    }

                    byte[] buffer = bos.toByteArray();
                    return buffer;
                } catch (IOException var14) {
                    throw new HttpCallerException(var14);
                } finally {
                    try {
                        if (ios != null) {
                            ios.close();
                        }

                        if (bos != null) {
                            bos.close();
                        }
                    } catch (IOException var13) {
                    }

                }
            }
        } else {
            throw new HttpCallerException("bad file to read:" + file);
        }
    }

    public static void recoveryFileFromBytes(byte[] body, String filePath, String fileName) throws HttpCallerException {
        try {
            String fileFullPath;
            if (filePath.endsWith("/")) {
                fileFullPath = filePath + fileName;
            } else {
                fileFullPath = filePath + "/" + fileName;
            }

            File f = new File(fileFullPath);
            FileOutputStream out = new FileOutputStream(f);

            try {
                out.write(body, 0, body.length);
                out.flush();
            } finally {
                if (out != null) {
                    out.close();
                }

            }

        } catch (Exception var10) {
            throw new HttpCallerException(var10);
        }
    }

    public static boolean isAsync() {
        boolean async = false;
        String asyncConf = System.getProperty("http.caller.connection.async");
        if (asyncConf != null && asyncConf.length() > 0) {
            async = Boolean.valueOf(asyncConf);
        }

        return async;
    }

    public static long getFutureGetTimeOut() {
        RequestConfig requestConfig = getRequestConfig();
        long waitTime = 0L;
        int socketTimeOUt = requestConfig.getSocketTimeout();
        if (socketTimeOUt > 0) {
            waitTime += (long)socketTimeOUt;
        }

        int crTimeOut = requestConfig.getConnectionRequestTimeout();
        if (crTimeOut > 0) {
            waitTime += (long)crTimeOut;
        }

        int connTimeOut = requestConfig.getConnectTimeout();
        if (connTimeOut > 0) {
            waitTime += (long)connTimeOut;
        }

        return (long)((double)waitTime * 1.1D);
    }
}
